<template>
  <div class="student-management app-container">
    <!-- 1. 搜索区域 + 添加按钮 -->
    <div class="search-bar">
      <el-row :gutter="20">
        <!-- 搜索表单 -->
        <el-col :span="16">
          <el-form
            :inline="true"
            :model="searchParams"
            class="search-form"
          >
            <el-form-item label="学号">
              <el-input
                v-model="searchParams.studentNo"
                placeholder="请输入学号"
                clearable
                style="width: 180px;"
              />
            </el-form-item>

            <el-form-item label="姓名">
              <el-input
                v-model="searchParams.studentName"
                placeholder="请输入姓名"
                clearable
                style="width: 180px;"
              />
            </el-form-item>

            <el-form-item label="班级">
              <el-input
                v-model="searchParams.className"
                placeholder="请输入班级"
                clearable
                style="width: 180px;"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>

        <!-- 添加按钮 -->
        <el-col :span="8" class="add-btn-container">
          <el-button
            type="success"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            添加学生
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 2. 学生表格 -->
    <el-table
      v-loading="loading"
      :data="studentList"
      border
      stripe
      @selection-change="handleSelectionChange"
      style="width: 100%; margin-top: 10px;"
    >
      <!-- 复选框列 -->
      <el-table-column type="selection" width="55" />

      <!-- 表格列 -->
      <el-table-column
        label="学号"
        prop="studentNo"
        align="center"
      />

      <el-table-column
        label="姓名"
        prop="studentName"
        align="center"
      />

      <el-table-column label="性别" prop="gender" align="center">
        <template slot-scope="scope">
          {{ scope.row.gender === '0' ? '女' : '男' }}
        </template>
      </el-table-column>

      <el-table-column
        label="年龄"
        prop="age"
        align="center"
      />

      <el-table-column
        label="班级"
        prop="className"
        align="center"
      />

      <el-table-column
        label="联系方式"
        prop="phone"
        align="center"
      />

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            size="small"
          >
            编辑
          </el-button>

          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.id)"
            size="small"
            style="color: #f56c6c;"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 3. 分页控件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.pageNum"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right;"
    />

    <!-- 4. 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        class="dialog-form"
      >
        <el-form-item label="学号" prop="studentNo">
          <el-input
            v-model="form.studentNo"
            placeholder="请输入学号"
            clearable
          />
        </el-form-item>

        <el-form-item label="姓名" prop="studentName">
          <el-input
            v-model="form.studentName"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="0">女</el-radio>
            <el-radio label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input
            v-model="form.age"
            placeholder="请输入年龄"
            type="number"
            min="1"
          />
        </el-form-item>

        <el-form-item label="班级" prop="className">
          <el-input
            v-model="form.className"
            placeholder="请输入班级"
            clearable
          />
        </el-form-item>

        <el-form-item label="联系方式" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入API请求方法
import {
  getStudentList,
  getStudentById,
  addStudent,
  updateStudent,
  deleteStudent
} from '@/api/student'

export default {
  name: "StudentManagement",
  data() {
    return {
      // 表格数据
      studentList: [],
      loading: false,
      selectedIds: [],

      // 搜索参数
      searchParams: {
        studentNo: '',
        studentName: '',
        className: ''
      },

      // 分页参数
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: '',
        studentNo: '',
        studentName: '',
        gender: '1',
        age: '',
        className: '',
        phone: ''
      },

      // 表单验证规则
      formRules: {
        studentNo: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { max: 20, message: '学号长度不能超过20个字符', trigger: 'blur' }
        ],
        studentName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        className: [
          { required: true, message: '请输入班级', trigger: 'blur' },
          { max: 50, message: '班级长度不能超过50个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 页面初始化加载列表
    this.getStudentList()
  },
  methods: {
    // 获取学生列表
    async getStudentList() {
      this.loading = true
      try {
        const params = {
          ...this.searchParams,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        const res = await getStudentList(params)
        this.studentList = res.data
        this.pagination.total = res.data.length
      } catch (error) {
        this.$message.error('获取学生列表失败，请重试！')
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.getStudentList()
    },

    // 重置
    handleReset() {
      this.searchParams = {
        studentNo: '',
        studentName: '',
        className: ''
      }
      this.pagination.pageNum = 1
      this.getStudentList()
    },

    // 每页条数变化
    handleSizeChange(pageSize) {
      this.pagination.pageSize = pageSize
      this.getStudentList()
    },

    // 页码变化
    handleCurrentChange(pageNum) {
      this.pagination.pageNum = pageNum
      this.getStudentList()
    },

    // 复选框选中
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(row => row.id)
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增学生'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef.resetFields()
        this.form = {
          id: '',
          studentNo: '',
          studentName: '',
          gender: '1',
          age: '',
          className: '',
          phone: ''
        }
      })
    },

    // 编辑
    async handleEdit(row) {
      this.dialogTitle = '编辑学生'
      this.$nextTick(() => {
        this.$refs.formRef.resetFields()
      })
      try {
        const res = await getStudentById(row.id)
        this.form = res.data
        this.dialogVisible = true
      } catch (error) {
        this.$message.error('获取学生详情失败！')
        console.error(error)
      }
    },

    // 提交
    async handleSubmit() {
      this.$refs.formRef.validate(async (isValid) => {
        if (!isValid) return
        try {
          if (this.form.id) {
            await updateStudent(this.form)
            this.$message.success('编辑成功！')
          } else {
            await addStudent(this.form)
            this.$message.success('新增成功！')
          }
          this.dialogVisible = false
          this.getStudentList()
        } catch (error) {
          const msg = this.form.id ? '编辑失败' : '新增失败'
          this.$message.error(`${msg}，请重试！`)
          console.error(error)
        }
      })
    },

    // 删除
    async handleDelete(id) {
      this.$confirm('此操作将永久删除该学生，是否继续？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await deleteStudent(id)
          this.$message.success('删除成功！')
          this.getStudentList()
        } catch (error) {
          this.$message.error('删除失败，请重试！')
          console.error(error)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped lang="scss">
.student-management {
  padding: 20px;
}

.search-bar {
  margin-bottom: 10px;
}

.add-btn-container {
  text-align: right;
}

.dialog-form {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
